package com.wait.onlinepicturecloud.application.service.impl;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.wait.onlinepicturecloud.shared.auth.StpKit;
import com.wait.onlinepicturecloud.shared.auth.model.SpaceUserPermissionConstant;
import com.wait.onlinepicturecloud.application.service.PictureApplicationService;
import com.wait.onlinepicturecloud.application.service.UserApplicationService;
import com.wait.onlinepicturecloud.domain.picture.entity.Picture;

import com.wait.onlinepicturecloud.domain.picture.service.PictureDomainService;
import com.wait.onlinepicturecloud.domain.picture.valueobject.PictureReviewStatusEnum;
import com.wait.onlinepicturecloud.domain.user.entity.User;

import com.wait.onlinepicturecloud.infrastructure.api.aliyunai.model.CreateOutPaintingTaskResponse;
import com.wait.onlinepicturecloud.infrastructure.config.LocalCacheConfig;
import com.wait.onlinepicturecloud.infrastructure.exception.ErrorCode;
import com.wait.onlinepicturecloud.infrastructure.exception.ThrowUtils;
import com.wait.onlinepicturecloud.infrastructure.mapper.PictureMapper;
import com.wait.onlinepicturecloud.interfaces.dto.picture.*;
import com.wait.onlinepicturecloud.interfaces.vo.picture.PictureVO;
import com.wait.onlinepicturecloud.interfaces.vo.user.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author Wait葡萄成熟时
 * @description 针对表【picture(图片)】的数据库操作Service实现
 * @createDate 2025-03-17 22:02:10
 */
@Slf4j
@Service
public class PictureApplicationServiceImpl extends ServiceImpl<PictureMapper, Picture>
        implements PictureApplicationService {


    @Resource
    private UserApplicationService userApplicationService;
    @Resource
    private PictureDomainService pictureDomainService;
    @Resource
    private LocalCacheConfig localCacheConfig;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * description 上传图片(url上传和普通上传)
     * author Wait葡萄成熟时
     * date 上午12:03 2025/3/19
     */
    @Override
    public PictureVO uploadPicture(Object inputSource, PictureUploadRequest pictureUploadRequest, User loginUser) {
      return pictureDomainService.uploadPicture(inputSource, pictureUploadRequest, loginUser);
    }


    /**
     * description 构建QueryWrapper查询
     * author Wait葡萄成熟时
     * date 上午10:29 2025/3/18
     */
    @Override
    public QueryWrapper<Picture> getQueryWrapper(PictureQueryRequest pictureQueryRequest) {
       return pictureDomainService.getQueryWrapper(pictureQueryRequest);
    }

    /**
     * description 获取单个图片封装
     * author Wait葡萄成熟时
     * date 下午11:55 2025/3/18
     */
    @Override
    public PictureVO getPictureVO(Picture picture, HttpServletRequest request) {

        // 将Picture转成PictureVO
        PictureVO pictureVO = PictureVO.objToVo(picture);
        // 关联查询用户信息
        Long userId = picture.getUserId();
        if (userId != null && userId > 0) {
            User user = userApplicationService.getUserById(userId);
            UserVO userVO = userApplicationService.getUserVO(user);
            pictureVO.setUser(userVO);
        }
        return pictureVO;
    }

    /**
     * description 分页获取图片封装
     * author Wait葡萄成熟时
     * date 上午12:02 2025/3/19
     */
    @Override
    public Page<PictureVO> getPictureVOPage(Page<Picture> picturePage, HttpServletRequest request) {
        List<Picture> pictureList = picturePage.getRecords();
        Page<PictureVO> pictureVOPage = new Page<>(picturePage.getCurrent(), picturePage.getSize(), picturePage.getTotal());
        if (CollUtil.isEmpty(pictureList)) {
            return pictureVOPage;
        }
        // 对象列表 => 封装对象列表
        List<PictureVO> pictureVOList = pictureList.stream().map(PictureVO::objToVo).collect(Collectors.toList());
        // 1. 关联查询用户信息
        Set<Long> userIdSet = pictureList.stream().map(Picture::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userApplicationService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 2. 填充信息
        pictureVOList.forEach(pictureVO -> {
            Long userId = pictureVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            pictureVO.setUser(userApplicationService.getUserVO(user));
        });
        pictureVOPage.setRecords(pictureVOList);
        return pictureVOPage;
    }




    /**
     * description 图片审核
     * author Wait葡萄成熟时
     * date 下午4:27 2025/3/26
     */
    @Override
    public void doPictureReview(PictureReviewRequest pictureReviewRequest, User loginUser) {
      pictureDomainService.doPictureReview(pictureReviewRequest, loginUser);
    }


    /**
     * description 给审核的图片设置审核参数
     * author Wait葡萄成熟时
     * date 下午4:43 2025/3/26
     */
    @Override
    public void fillReviewParams(Picture picture, User loginUser) {
        pictureDomainService.fillReviewParams(picture, loginUser);
    }

    /**
     * description 批量抓取和创建图片
     * author Wait葡萄成熟时
     * date 上午12:46 2025/3/28
     */
    @Override
    public int uploadPictureByBatch(PictureUploadByBatchRequest pictureUploadByBatchRequest, User loginUser) {
       return pictureDomainService.uploadPictureByBatch(pictureUploadByBatchRequest, loginUser);
    }

    /**
     * description 清理图片
     * author Wait葡萄成熟时
     */
    @Async//异步方法
    @Override
    public void clearPictureFile(Picture oldPicture) {
       pictureDomainService.clearPictureFile(oldPicture);
    }

    /**
     * description 空间的图片权限控制(管理员和本人可用）
     * author Wait葡萄成熟时
     */
    @Override
    public void checkPictureAuth(User loginUser, Picture picture) {
     pictureDomainService.checkPictureAuth(loginUser, picture);
    }

    /**
     * description 删除图片（较多业务，单独抽出）
     * author Wait葡萄成熟时
     */
    @Override
    public void deletePicture(long pictureId, User loginUser) {
  pictureDomainService.deletePicture(pictureId, loginUser);
    }

    /**
     * description 编辑图片（较多业务，单独抽出）
     * author Wait葡萄成熟时
     */
    @Override
    public void editPicture(PictureEditRequest pictureEditRequest, User loginUser) {
 pictureDomainService.editPicture(pictureEditRequest, loginUser);
    }

    /**
     * description 图片分页查询带缓存（较多业务，单独抽出）
     * author Wait葡萄成熟时
     */
    @Override
    public Page<PictureVO> listPictureVOByPage(PictureQueryRequest pictureQueryRequest, HttpServletRequest request) {
        long current = pictureQueryRequest.getCurrent();
        long size = pictureQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 空间权限校验
        Long spaceId = pictureQueryRequest.getSpaceId();
        // 公开图库
        if (spaceId == null) {
            // 普通用户默认只能查看已过审的公开数据
            pictureQueryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            pictureQueryRequest.setNullSpaceId(true);
        } else {

            // 编程式校验权限
            boolean b = StpKit.SPACE.hasPermission(SpaceUserPermissionConstant.PICTURE_VIEW);
            ThrowUtils.throwIf(!b, ErrorCode.NO_AUTH_ERROR);
//            // 私有空间
//            User loginUser = userService.getLoginUser(request);
//            Space space = spaceService.getById(spaceId);
//            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
//            if (!loginUser.getId().equals(space.getUserId())) {
//                throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间权限");
//            }
        }


        if (spaceId == null) {
            /*二级缓存*/
            // 构建缓存 key
            String queryCondition = JSONUtil.toJsonStr(pictureQueryRequest);
            String hashKey = DigestUtils.md5DigestAsHex(queryCondition.getBytes());
            String cacheKey = "yupicture:listPictureVOByPage:" + hashKey;

            // 1. 查询本地缓存（Caffeine）
            String cachedValue = localCacheConfig.getLOCAL_CACHE().getIfPresent(cacheKey);
            if (cachedValue != null) {
                Page<PictureVO> cachedPage = JSONUtil.toBean(cachedValue, Page.class);
                return cachedPage;
            }
            // 2. 查询分布式缓存（Redis）
            ValueOperations<String, String> valueOps = stringRedisTemplate.opsForValue();
            cachedValue = valueOps.get(cacheKey);
            if (cachedValue != null) {
                // 如果命中 Redis，存入本地缓存并返回
                localCacheConfig.getLOCAL_CACHE().put(cacheKey, cachedValue);
                Page<PictureVO> cachedPage = JSONUtil.toBean(cachedValue, Page.class);
                return cachedPage;
            }


            // 3.查询数据库
            Page<Picture> picturePage = this.page(new Page<>(current, size),
                    this.getQueryWrapper(pictureQueryRequest));
            // 获取封装类
            Page<PictureVO> pictureVOPage = this.getPictureVOPage(picturePage, request);
            // 4. 更新缓存
            String cacheValue = JSONUtil.toJsonStr(pictureVOPage);
            // 更新本地缓存
            localCacheConfig.getLOCAL_CACHE().put(cacheKey, cacheValue);
            // 更新 Redis 缓存，设置过期时间为 5 分钟
            valueOps.set(cacheKey, cacheValue, 1, TimeUnit.MINUTES);

            return pictureVOPage;

        } else {
            // 3.查询数据库
            Page<Picture> picturePage = this.page(new Page<>(current, size),
                    this.getQueryWrapper(pictureQueryRequest));
            // 获取封装类
            Page<PictureVO> pictureVOPage = this.getPictureVOPage(picturePage, request);

            return pictureVOPage;
        }


    }

    /**
     * description 按颜色查询图片
     * author Wait葡萄成熟时
     */
    @Override
    public List<PictureVO> searchPictureByColor(Long spaceId, String picColor, User loginUser) {
      return pictureDomainService.searchPictureByColor(spaceId, picColor, loginUser);
    }

    /**
     * description    批量修改图片
     * author Wait葡萄成熟时
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editPictureByBatch(PictureEditByBatchRequest pictureEditByBatchRequest, User loginUser) {
  pictureDomainService.editPictureByBatch(pictureEditByBatchRequest, loginUser);

    }


    /**
     * description
     * author Wait葡萄成熟时
     * 创建扩图任务
     */
    @Override
    public CreateOutPaintingTaskResponse createPictureOutPaintingTask(CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest, User loginUser) {
        return pictureDomainService.createPictureOutPaintingTask(createPictureOutPaintingTaskRequest, loginUser);
    }
    @Override
    public void validPicture(Picture picture) {
        pictureDomainService.validPicture(picture);
    }

}




